//
//  MyButtonLayer.m
//  ButtonCocos2D
//
//  Created by admin on 3/23/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "MyButtonLayer.h"

@implementation MyButtonLayer

-(void) step {
	[_message setString:@"Buttons pressed:"];
	for(MyGameButton *b in _buttons){
		if(b.pressed){
			[_message setString:[NSString stringWithFormat:@"%@ %@",_message.string,b.name]];
		}
	}
}

-(void) createButtonWithPosition:(CGPoint)position withUpFrame:(NSString*)upFrame withDownFrame:(NSString*)downFrame withName:(NSString*)name {
	CCSpriteFrameCache *cache = [CCSpriteFrameCache sharedSpriteFrameCache];
	
	MyGameButton *button = [[MyGameButton alloc] init];
	button.position = position;
	[button setUpSpriteFrame:upFrame];
	[button setDownSpriteFrame:downFrame];
	[button setDisplayFrame:[cache spriteFrameByName:[button upSpriteFrame]]];
	button.name = name;
	[self addChild:button];
	[_buttons addObject:button];
}

-(void) ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {	
	UITouch *touch = [touches anyObject];
    CGPoint point = [touch locationInView: [touch view]];
	point = [[CCDirector sharedDirector] convertToGL: point];
	
	for(MyGameButton *b in _buttons){
		[b ccTouchesBegan:touches withEvent:event];
	}
}
-(void) ccTouchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {	
	UITouch *touch = [touches anyObject];
    CGPoint point = [touch locationInView: [touch view]];
	point = [[CCDirector sharedDirector] convertToGL: point];
    
	for(MyGameButton *b in _buttons){
		[b ccTouchesMoved:touches withEvent:event];
	}
}
-(void) ccTouchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {	
	UITouch *touch = [touches anyObject];
    CGPoint point = [touch locationInView: [touch view]];
	point = [[CCDirector sharedDirector] convertToGL: point];
    
	for(MyGameButton *b in _buttons){
		[b ccTouchesEnded:touches withEvent:event];
	}
}



-(CCLayer*) runRecipe
{
    self.isTouchEnabled = YES;
    _message = [CCLabelBMFont labelWithString:@"Buttons pressed: " 
                                      fntFile:@"eurostile_30.fnt"];
    _message.position = ccp(240,260);
	_message.scale = 0.75f;
	[self addChild:_message];
    
    CCSpriteFrameCache *cache = [CCSpriteFrameCache sharedSpriteFrameCache];
	
	[cache addSpriteFramesWithFile:@"dpad_buttons.plist"];
    
	_buttons = [[NSMutableArray alloc] init];
    
	[self createButtonWithPosition:ccp(350,50) withUpFrame:@"b_button_up.png" withDownFrame:@"b_button_down.png" withName:@"B"];
	[self createButtonWithPosition:ccp(400,100) withUpFrame:@"a_button_up.png" withDownFrame:@"a_button_down.png" withName:@"A"];
	[self createButtonWithPosition:ccp(350,150) withUpFrame:@"x_button_up.png" withDownFrame:@"x_button_down.png" withName:@"X"];
	[self createButtonWithPosition:ccp(300,100) withUpFrame:@"y_button_up.png" withDownFrame:@"y_button_down.png" withName:@"Y"];
    
	[self schedule:@selector(step)];
    
    return self;
}

@end
